<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue';
import { NModal, NCard, NSpace, NSpin, useMessage } from 'naive-ui';
import * as echarts from 'echarts';
import type { EChartsOption } from 'echarts';
import { fetchTagStatistics, type TagStatisticsDTO } from '@/service/api/dataplatform/tag';

const message = useMessage();

const visible = ref(false);
const loading = ref(false);
const statistics = ref<TagStatisticsDTO[]>([]);

const usageChartRef = ref<HTMLDivElement>();
const assetChartRef = ref<HTMLDivElement>();

let usageChart: echarts.ECharts | null = null;
let assetChart: echarts.ECharts | null = null;

/**
 * 打开弹窗
 */
async function open() {
  visible.value = true;
  await loadStatistics();
  await nextTick();
  initCharts();
}

/**
 * 加载统计数据
 */
async function loadStatistics() {
  loading.value = true;
  try {
    const { data } = await fetchTagStatistics();
    statistics.value = data || [];
  } catch (error) {
    message.error('加载统计数据失败');
  } finally {
    loading.value = false;
  }
}

/**
 * 初始化图表
 */
function initCharts() {
  if (!usageChartRef.value || !assetChartRef.value) return;

  // 使用次数图表
  usageChart = echarts.init(usageChartRef.value);
  const usageOption: EChartsOption = {
    title: {
      text: '标签使用次数 TOP 10',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: statistics.value.slice(0, 10).map(item => item.tagName),
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '使用次数'
    },
    series: [
      {
        name: '使用次数',
        type: 'bar',
        data: statistics.value.slice(0, 10).map(item => item.usageCount),
        itemStyle: {
          color: '#1890ff'
        }
      }
    ]
  };
  usageChart.setOption(usageOption);

  // 关联资产数量图表
  assetChart = echarts.init(assetChartRef.value);
  const assetOption: EChartsOption = {
    title: {
      text: '标签关联资产数量 TOP 10',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: statistics.value.slice(0, 10).map(item => item.tagName),
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '资产数量'
    },
    series: [
      {
        name: '资产数量',
        type: 'bar',
        data: statistics.value.slice(0, 10).map(item => item.assetCount),
        itemStyle: {
          color: '#52c41a'
        }
      }
    ]
  };
  assetChart.setOption(assetOption);

  // 响应式调整
  window.addEventListener('resize', handleResize);
}

/**
 * 处理窗口大小变化
 */
function handleResize() {
  usageChart?.resize();
  assetChart?.resize();
}

/**
 * 关闭弹窗
 */
function handleClose() {
  visible.value = false;
  window.removeEventListener('resize', handleResize);
  usageChart?.dispose();
  assetChart?.dispose();
  usageChart = null;
  assetChart = null;
}

defineExpose({
  open
});

</script>

<template>
  <NModal
    v-model:show="visible"
    preset="card"
    title="标签统计"
    :style="{ width: '1200px' }"
    @after-leave="handleClose"
  >
    <NSpin :show="loading">
      <NSpace vertical :size="24">
        <NCard>
          <div ref="usageChartRef" style="width: 100%; height: 400px"></div>
        </NCard>

        <NCard>
          <div ref="assetChartRef" style="width: 100%; height: 400px"></div>
        </NCard>
      </NSpace>
    </NSpin>
  </NModal>
</template>
